<?php

$data = isset($_POST['data']) ? $_POST['data'] : null;
if (is_null($data)) {
    echo ("Les données sont NULL");
    die;
}
$lignes = explode(PHP_EOL, $data);
$dayName = array('lundi' => 1, 'mardi' => 7, 'mercredi' => 13, 'jeudi' => 19, 'vendredi' => 25, 'samedi' => 31, 'dimanche' => 37);
$codec = array(
    'P' => '1',
    'CP' => '2',
    'OFF' => '3',
    'IND' => '4',
    'ABS' => '5',
    'CSS' => '6',
    'TE' => '7',
    'TS' => '8',
    'AM1' => '9',
    'AM2' => '10',
    'AT' => '11',
    'EF' => '22',
    'F1' => '13',
    'F2' => '14',
    'F' => '15',
    'CM' => '16',
    'DA' => '17',
    'RT' => '18',
    'PRDA' => '19',
    'CPEXP' => '20',
    'CMP' => '21',
    'EFI' => '22',
    'EFE' => '23',
    'EFA' => '24',
    'ES' => '26',
);
foreach ($lignes as $l) {
    $csv = str_getcsv($l, ';');
    if (count($csv) > 5) {
        $sql = 'UPDATE rh_planning_semaine SET ';
        //var_dump($csv);
        foreach ($dayName as $day => $value) {
            $dayCode = $day . '_code';

            $dayEntree = $day . '_entree';
            $daySortie = $day . '_sortie';
            $dayPause = $day . '_pause';
            $dayRepas = $day . '_repas';
            $code = (!isset($csv[$value + 1]) || $csv[$value + 1] == '') ? 'IND' : $csv[$value + 1];
            $code = isset($codec[$code]) ? $codec[$code] : $codec['IND'];
            $entree = (!isset($csv[$value + 2]) || $csv[$value + 2] == '') ? '00:00' : $csv[$value + 2];
            $sortie = (!isset($csv[$value + 3]) || $csv[$value + 3] == '') ? '00:00' : $csv[$value + 3];
            $pause = !isset($csv[$value + 4]) || (int) $csv[$value + 4] != 0 ? 1 : 0;
            $repas = !isset($csv[$value + 5]) || (int) $csv[$value + 5] != 0 ? 1 : 0;
            $sql .= ($day != 'lundi') ? ', ' : ' ';
            $sql .= "$dayCode = $code, $dayEntree = '$entree', $daySortie = '$sortie', $dayPause = $pause, $dayRepas = $repas";
        }
        $sql .= " WHERE matricule = {$csv[0]} AND lundi = '{$csv[1]}';";
        if ($csv[0] == '' || $csv[1] == '')
            continue;
        echo $sql . '<br><br>';
    }
}